package wwiii;

import java.util.ArrayList;
import java.util.Collection;
import java.util.TreeSet;

import javax.jdo.annotations.PersistenceCapable;
import javax.jdo.annotations.Persistent;
import javax.jdo.annotations.PrimaryKey;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

@PersistenceCapable(detachable = "true")
public class Player {
	public static Key getKey(String name) {
		return KeyFactory.createKey(Player.class.getSimpleName(), name);
	}

	@PrimaryKey
	@Persistent
	private Key key;

	@Persistent
	private String id;

	@Persistent
	private String mail;

	@Persistent
	private String name;

	@Persistent
	private int rank;

	@Persistent
	private Collection<String> games = new TreeSet<String>();

	public Player(String id, String mail, String name, int rank) {
		this.key  = getKey(id);
		this.id   = id;
		this.mail = mail;
		this.name = name;
		this.rank = rank;
	}

	public Key getKey() { return key; }
	public String getId() { return id; }
	public String getMail() { return mail; }
	public String getName() { return name; }
	public int getRank() { return rank; }

	public Collection<String> getGames() {
		return new ArrayList<String>(games);
	}
	public void addGame(Game game) {
		for (String g : games) {
			if (g.equals(game.getId())) return;
		}

		games.add(game.getId());
	}
	public void removeGame(Game game) {
		games.remove(game.getId());
	}

	@Override
	public boolean equals(Object obj) {
		if (obj instanceof Player) {
			return equals((Player) obj);
		}

		return false;
	}
	private boolean equals(Player that) {
		if (key == null && that.key == null) return true;

		return this.key.equals(that.key);
	}

	@Override
	public int hashCode() {
		return key.hashCode();
	}

	@Override
	public String toString() {
		return "[Player "+ key +" "+ mail +" "+ name +" "+ rank +"]";
	}
}
